package bhwz.seac3.bl.import_;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

import org.junit.Test;

import bhwz.seac3.blservice.import_.ErrorLogPrinter;
import bhwz.seac3.db.nbadata.SaveQueryDB;
import bhwz.seac3.dbservice.nbadata.SaveQueryDBService;
import bhwz.seac3.po.TeamIconPo;
import bhwz.seac3.po.TeamPo;
import bhwz.seac3.util.SVGManager;

public class TeamImportBL{

	public void importTeam(String path, ErrorLogPrinter elp) {
		if (Data.isValid(path)) {
			Data.withAllData(Data.getFiles(path), file -> {
				return file.getName().equals("teams") ? true : false;
			}, file -> {
				List<TeamPo> teamPos = _teamPo(file);
				teamPos.forEach(s -> {
					try {
						SaveQueryDBService<TeamPo> db = new SaveQueryDB<>();
						db.save(s);
					} catch (Exception e) {
						e.printStackTrace();
					}
				});
			}, elp);
			SaveQueryDBService<TeamIconPo> db = new SaveQueryDB<>();
			Data.withAllData(Data.getFiles(path), file -> {
				return file.getName().matches(".*(\\.svg)$") ? true : false;
			}, file -> {
				try {
					db.save(_teamIconPo(file));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}, elp);
		} else {
			elp.print("ivvalid path!");
		}
	}

	private List<TeamPo> _teamPo(File file) {
		List<TeamPo> teams = new LinkedList<TeamPo>();

		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
			String line = br.readLine();
			while (line != null) {
				if (Pattern.compile("\\w").matcher(line).find()) {
					String line2 = line.replaceAll("\\s│", "│")
							.replaceAll("║", "");
					String[] teamItem = line2.split("│");
					TeamPo teamPo = new TeamPo();
					teamPo.set球队全名(teamItem[0]);
					teamPo.set缩写(teamItem[1]);
					teamPo.set所在地(teamItem[2]);
					teamPo.set赛区(teamItem[3]);
					teamPo.set分区(teamItem[4]);
					teamPo.set主场(teamItem[5]);
					teamPo.set建立时间(teamItem[6]);
					teams.add(teamPo);
				}
				line = br.readLine();
			}
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return teams;
	}

	private TeamIconPo _teamIconPo(File file) {
		TeamIconPo po = new TeamIconPo();
		po.setKey(file.getName().substring(0,file.getName().indexOf(".")));
		po.setPicture(new SVGManager().encodeImage(file.getPath()));
		return po;
	}
	@Test
	public void test_PlayerPO(){
		TeamImportBL bl=new TeamImportBL();
		bl.importTeam("/home/ivan/teams", s->System.out.println(s));
	}
}
